package com.lzb.musicplayer.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lzb.basic.dialog.PermissionExplainDialog;
import com.lzb.musicplayer.BaseAc;
import com.lzb.musicplayer.BasePlayerActivity;
import com.lzb.musicplayer.HomeActivity;
import com.lzb.musicplayer.R;
import com.lzb.musicplayer.adapter.MusicAdapter;
import com.lzb.musicplayer.bean.GroupMusicInfo;
import com.lzb.musicplayer.bean.MusicFile;
import com.lzb.musicplayer.databinding.ActivityRecentAddBinding;
import com.lzb.musicplayer.dialog.DeleteDialog;
import com.lzb.musicplayer.dialog.MusicEditDialog;
import com.lzb.musicplayer.dialog.PlaylistDialog;
import com.lzb.musicplayer.utils.MusicScanner;
import com.lzb.musicplayer.utils.MusicScannerUtil;
import com.lzb.musicplayer.utils.RingtoneUtil;
import com.lzb.musicplayer.utils.SaveListUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class RecentAddActivity extends BasePlayerActivity<ActivityRecentAddBinding> implements View.OnClickListener, OnItemClickListener, OnItemChildClickListener {

    private MusicAdapter musicAdapter;
    private List<MusicFile> listShow = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.activity_recent_add;
    }

    @Override
    protected void initView() {
        mDataBinding.ivRecentAddBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.llGetPermission.setOnClickListener(this);
        mDataBinding.llPlay.setOnClickListener(this);
        mDataBinding.llRandomPlay.setOnClickListener(this);

        mDataBinding.rvMusicList.setLayoutManager(new LinearLayoutManager(mContext));
        musicAdapter = new MusicAdapter();
        mDataBinding.rvMusicList.setAdapter(musicAdapter);
        musicAdapter.addChildClickViewIds(R.id.ivMusicItemEdit);
        musicAdapter.setOnItemClickListener(this);
        musicAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.llGetPermission) {//申请权限
            getPermission();
        } else if (id == R.id.llPlay) {//播放全部
            setFragmentMusicList(listShow);
        } else if (id == R.id.llPlay) {//随机播放
            if (listShow.size() == 0) return;
            mDataBinding.audioPlayerView.setSj();
            mDataBinding.audioPlayerView.startPlay();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        GroupMusicInfo groupMusicInfo = musicAdapter.getData().get(position);
        List<MusicFile> list = groupMusicInfo.getList();
        Intent intent = new Intent(RecentAddActivity.this, AlbumInfoActivity.class);
        intent.putExtra("list", (Serializable) list);
        startActivity(intent);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        int id = view.getId();
        if (id == R.id.ivMusicItemEdit) {
            showEditDialog(view, musicAdapter.getItem(position).getList());
        }
    }

    @Override
    protected void initData() {
        boolean hasPermission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            hasPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_MEDIA_AUDIO)
                    == PackageManager.PERMISSION_GRANTED;
        } else {
            hasPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED;
        }
        if (hasPermission) {
            getPermission();
            mDataBinding.llGetPermission.setVisibility(View.GONE);
        } else {
            mDataBinding.llGetPermission.setVisibility(View.VISIBLE);
            mDataBinding.tvMusicNoData.setVisibility(View.GONE);
        }
    }

    private void getPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_audio_permission));
        List<String> permissionsInManifest = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissionsInManifest.add(Manifest.permission.READ_MEDIA_AUDIO);
        } else {
            permissionsInManifest.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            permissionsInManifest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        PermissionUtils.permission(permissionsInManifest.toArray(new String[permissionsInManifest.size()])).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                getData();
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    private void getData() {
        showDialog(getString(R.string.loading));
        new MusicScannerUtil().loadMusicFiles(this, new MusicScannerUtil.OnCallBackListener() {
            @Override
            public void onCallBack(List<MusicFile> list) {
                dismissDialog();
                if (list != null && list.size() > 0) {
                    listShow.clear();
                    for (MusicFile musicFile : list) {
                        long now = TimeUtils.getNowMills();
                        long time = now - FileUtils.getFileLastModified(musicFile.getPath());
                        if (time <= 7 * 24 * 60 * 60 * 1000L) {
                            listShow.add(musicFile);
                        }
                    }
                    mDataBinding.audioPlayerView.setPlayList(listShow, 0);
                    setList(listShow);
                } else {
                    mDataBinding.rvMusicList.setVisibility(View.VISIBLE);
                    mDataBinding.tvMusicNoData.setVisibility(View.GONE);
                }
            }
        });
    }

    public void setList(List<MusicFile> files) {
        List<GroupMusicInfo> groupedList = MusicScanner.groupByProperty(RecentAddActivity.this, files);
        if (groupedList != null && groupedList.size() > 0) {
            musicAdapter.setList(groupedList);
            mDataBinding.rvMusicList.setVisibility(View.VISIBLE);
            mDataBinding.tvMusicNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvMusicList.setVisibility(View.GONE);
            mDataBinding.tvMusicNoData.setVisibility(View.VISIBLE);
        }

    }

    private void showEditDialog(View view, List<MusicFile> musicFile) {
        MusicEditDialog dialog = new MusicEditDialog(mContext);
        BasePopupView basePopupView = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .offsetX(0)//x轴偏移
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(view).hasShadowBg(false) // 去掉半透明背景
                .asCustom(dialog);
        dialog.setListener(new MusicEditDialog.Ilistener() {
            @Override
            public void clickItem(int pos) {
                switch (pos) {
                    case 0://播放
                        setFragmentMusicList(musicFile);
                        break;
                    case 1://加入播放队列
                        SaveListUtils.saveDlList(RecentAddActivity.this, musicFile);
                        break;
                    case 2://加入播放列表
                        showPlaylistDialog(musicFile);
                        break;
                    case 3://设为铃声
                        RingtoneUtil.setRingtone(mContext, musicFile.get(0).getPath(), RingtoneManager.TYPE_RINGTONE);
                        break;
                    case 4://删除
                        showDeleteDialog(musicFile);
                        break;
                }
            }
        });
        basePopupView.show();
    }

    private void showDeleteDialog(List<MusicFile> musicFile) {
        DeleteDialog dialog = new DeleteDialog(mContext);
        dialog.setText(getString(R.string.music_delete_tip));
        dialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                setDelete(musicFile);
            }
        });
        dialog.show();
    }

    private void setDelete(List<MusicFile> list) {
        if (list != null && !list.isEmpty()) {
            FileUtils.delete(list.get(0).getPath());
            getData();
        }
    }

    private void showPlaylistDialog(List<MusicFile> musicFile) {
        PlaylistDialog playlistDialog = new PlaylistDialog(mContext);
        playlistDialog.setMusicFileList(musicFile);
        playlistDialog.show();
    }

    private void setFragmentMusicList(List<MusicFile> listFile) {
        if (listFile != null && !listFile.isEmpty()) {
            mDataBinding.audioPlayerView.setPlayList(listFile, 0);
            mDataBinding.audioPlayerView.startPlay();
        }
    }

    @Override
    public void onPlaybackStateChanged(boolean isPlaying) {
        if (isPlaying) {
            mDataBinding.audioPlayerView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPlaybackStateChanged(int state) {

    }

    @Override
    public void onProgressUpdated(long position, long duration) {

    }

    @Override
    public void onTrackChanged(MusicFile currentTrack) {

    }
}